<template>
  <div>
    <div
      style="
        padding: 24px 24px 12px 12px;
        display: flex;
        align-items: center;
        justify-content: space-between;
      "
    >
      <!-- <h1>Contacts</h1> -->
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
        "
      >
        <!-- <el-button :type="inputKeyword != '' ? 'warning' : 'info'" link>
          <el-icon :size="18"><Search /></el-icon>
          <span>搜索</span>
        </el-button> -->
        <el-input
          style="
            margin-right: 16px;
            width: 240px;
            min-width: 240px;
            border-radius: auto;
          "
          v-model="inputKeyword"
          size="large"
          placeholder="汉字、拼音、首字母"
          prefix-icon="Search"
          clearable
          autofocus
        ></el-input>
        <!-- <span style="min-width: 36px">
          <el-button
            v-show="inputKeyword != ''"
            type="warning"
            size="small"
            circle
            :disabled="inputKeyword == ''"
            @click="inputKeyword = ''"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </span> -->
        <el-alert
          style="background-color: transparent"
          show-icon
          :closable="false"
          :type="contactsFiltered.length == 0 ? 'warning' : 'success'"
          :title="
            `找到${contactsFiltered.length}个联系人` +
            (inputKeyword.length > 0
              ? `（关键字：${inputKeyword}）`
              : selectedTag != null
              ? selectedTag != ''
                ? `（标签：${selectedTag}）`
                : '（无标签）'
              : '')
          "
        ></el-alert>
      </div>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100px;
          min-width: 100px;
        "
      >
        <el-tooltip content="新建联系人" placement="top">
          <el-button @click="edit()" type="primary" size="small" circle>
            <el-icon><Plus /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="导出Excel文档" placement="top">
          <el-button
            @click="download()"
            type="success"
            size="small"
            circle
            :disabled="contactsFiltered.length == 0"
          >
            <el-icon><Download /></el-icon>
          </el-button>
        </el-tooltip>
        <el-tooltip content="刷新数据" placement="top">
          <el-button @click="load(true)" type="info" size="small" circle>
            <el-icon><Refresh /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>
    <div style="padding: 12px; padding-right: 20px">
      <el-card shadow="hover" style="border-radius: auto">
        <el-button
          type="success"
          size="small"
          :plain="selectedTag != null"
          @click="selectedTag = null"
          >全部</el-button
        >
        <el-button
          v-for="tag in tags"
          type="primary"
          size="small"
          :plain="selectedTag != tag"
          @click="selectedTag = tag"
          >#{{ tag }}</el-button
        >
        <el-button
          type="warning"
          size="small"
          :plain="selectedTag != ''"
          @click="selectedTag = ''"
          >无标签</el-button
        >
      </el-card>
    </div>
    <!-- <div style="padding: 0 12px"></div> -->
    <div style="padding-right: 8px; column-count: 3; column-gap: 10px">
      <div v-for="(item, index) in contactsFiltered">
        <div style="padding: 16px 12px">
          <el-card shadow="hover" style="border-radius: auto">
            <template #header>
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                "
              >
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                  "
                >
                  <div
                    style="
                      padding-right: 12px;
                      font-size: 20px;
                      font-weight: bold;
                    "
                  >
                    {{ item.name }}
                  </div>
                  <div>
                    <el-tag v-for="tag in item.tags">
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>

                <el-button type="info" link @click="edit(index)">
                  <el-icon><EditPen /></el-icon>
                </el-button>
              </div>
            </template>
            <div>
              <div
                v-for="(phone, pid) in item.phones"
                style="
                  padding: 8px 0;
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                "
              >
                <div style="color: rgba(128, 128, 128, 1)">
                  {{ phone.title }}
                </div>
                <div style="font-size: 24px; font-weight: bold">
                  {{ parseTel(phone.number) }}
                </div>

                <el-button
                  :type="phone.nonlocal ? 'warning' : 'primary'"
                  size="small"
                  plain
                  @click="toggle(index, pid)"
                >
                  {{ phone.nonlocal ? "外埠" : "本埠" }}
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="showEdit"
      width="480px"
      :title="editItem && editItem.uid ? '编辑联系人' : '新建联系人'"
      draggable
      append-to-body
      destroy-on-close
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div v-if="editItem">
        <div>
          <el-form>
            <el-form-item label="姓名">
              <el-input v-model="editItem.name" style="width: 100%"></el-input>
            </el-form-item>
            <el-form-item label="标签">
              <el-select
                v-model="editItem.tags"
                multiple
                filterable
                allow-create
                default-first-option
                :reserve-keyword="false"
                placeholder="选择标签或输入新标签"
                style="width: 100%"
              >
                <el-option
                  v-for="item in tags"
                  :key="'#' + item"
                  :label="'#' + item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-for="(phone, pid) in editItem.phones">
              <el-button link type="primary" style="margin: 4px" @click="add()">
                <el-icon><CirclePlusFilled /></el-icon>
              </el-button>
              <el-button
                link
                type="danger"
                style="margin: 4px"
                :disabled="editItem.phones.length == 1"
                @click="remove(pid)"
              >
                <el-icon><RemoveFilled /></el-icon>
              </el-button>
              <span style="width: 100px; padding-left: 12px">
                <el-select v-model="editItem.phones[pid].title" allow-create>
                  <el-option
                    v-for="title in phoneTitles"
                    :key="'~' + title"
                    :label="title"
                    :value="title"
                  ></el-option>
                </el-select>
              </span>
              <span style="width: 200px; padding: 0 12px">
                <el-input v-model="editItem.phones[pid].number"></el-input>
              </span>
              <span style="width: 60px">
                <el-checkbox v-model="editItem.phones[pid].nonlocal"
                  >外埠</el-checkbox
                >
              </span>
            </el-form-item>
          </el-form>
        </div>
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-top: 12px;
          "
        >
          <span>
            <el-button
              type="primary"
              @click="save('save')"
              :disabled="!editValid"
              >保存</el-button
            >
            <el-button @click="save('cancel')" link>取消</el-button>
          </span>
          <el-popconfirm title="确认删除?" @confirm="save('delete')">
            <template #reference>
              <el-button type="warning" link :disabled="!editItem.uid"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, computed, onMounted, onUnmounted } from "vue";
import { ElNotification } from "element-plus";
import PinYinMatch from "pinyin-match";
import * as XLSX from "xlsx";
import dateFormat from "@/utils/dateFormat.js";
const contactsFull = ref([]);
const contactsFiltered = computed(() =>
  inputKeyword.value == "" && selectedTag.value == null
    ? contactsFull.value
    : contactsFull.value.filter((item) =>
        inputKeyword.value != ""
          ? PinYinMatch.match(item.name, inputKeyword.value)
            ? true
            : false
          : selectedTag.value == null
          ? true
          : selectedTag.value == ""
          ? item.tags.length == 0
            ? true
            : false
          : item.tags.includes(selectedTag.value)
          ? true
          : false
      )
);
const selectedTag = ref(null);
const inputKeyword = ref("");
const showEdit = ref(false);
const API_URL = "api/contacts_handler.php";

const editItem = ref();
let editItemBackup = "";
const editValid = computed(
  () =>
    editItemBackup != JSON.stringify(editItem.value) &&
    editItem.value.name.length >= 2 &&
    editItem.value.phones[0].number.length >= 4
);
const edit = (index = -1) => {
  if (index < 0) {
    // add
    editItem.value = {
      name: "",
      tags: [],
      phones: [{ title: "手机", number: "", nonlocal: false }],
    };
  } else {
    // edit
    editItem.value = JSON.parse(JSON.stringify(contactsFiltered.value[index]));
  }
  editItemBackup = JSON.stringify(editItem.value);
  showEdit.value = true;
};
const save = (method = "save") => {
  if (method == "save" || method == "delete") {
    axios
      .post(API_URL, {
        action:
          method == "save" ? (editItem.value.uid ? "modify" : "add") : "remove",
        uid: editItem.value.uid ? editItem.value.uid : null,
        contact: method == "save" ? editItem.value : null,
      })
      .then((response) => {
        if (response.data.result) {
          ElNotification({
            title: "已保存",
            // message: "",
            type: "success",
          });
        } else {
          ElNotification({
            title: "数据库出错了",
            // message: "",
            type: "error",
          });
        }
        load();
      })
      .catch((error) => {
        ElNotification({
          title: "请求出错了",
          message: JSON.stringify(error, null, 2),
          type: "error",
        });
      });
  }
  showEdit.value = false;
  setTimeout(() => {
    editItem.value = null;
    editItemBackup = "";
  }, 500);
};
const remove = (pid) => {
  editItem.value.phones.splice(pid, 1);
};
const add = () => {
  editItem.value.phones.push({ title: "手机", number: "", nonlocal: false });
};
const toggle = (idx, pid) => {
  let payload = {
    action: "local",
    nonlocal: contactsFiltered.value[idx].phones[pid].nonlocal
      ? "false"
      : "true",
    uid: contactsFiltered.value[idx].uid,
    pid,
  };
  axios
    .post(API_URL, payload)
    .then((response) => {
      if (response.data.result) {
        ElNotification({
          title: "已保存",
          // message: "",
          type: "success",
        });
      } else {
        ElNotification({
          title: "数据库出错了",
          // message: "",
          type: "error",
        });
      }
      load();
    })
    .catch();
};

const load = (notify) => {
  axios
    .get(API_URL)
    .then((response) => {
      if (notify) {
        ElNotification({
          title: "通讯录已刷新",
          message: `查找到${response.data.length}个联系人`,
          type: response.data.length > 0 ? "success" : "warning",
        });
      }
      contactsFull.value = response.data;
    })
    .catch((error) => {
      ElNotification({
        title: "请求出错了",
        message: JSON.stringify(error, null, 2),
        type: "error",
      });
      console.error(error);
    });
};

const tags = computed(() => {
  if (contactsFull.value.length == 0) return [];
  let tags = [];
  contactsFull.value.forEach((item) => {
    tags.push(...item.tags);
  });
  tags = [...new Set(tags)];
  tags = tags.sort(function compareFunction(param1, param2) {
    return param1.localeCompare(param2, "zh");
  });
  return tags;
});

const phoneTitles = ref(["手机", "座机", "办公", "家", "其他"]);

const download = () => {
  const cells = [];
  for (let i = 0; i < contactsFiltered.value.length; i++) {
    let contact = contactsFiltered.value[i];
    let cell = {};
    cell["姓名"] = contact.name;
    cell["标签"] = contact.tags.join(",");
    for (let j = 0; j < contact.phones.length; j++) {
      let phone = contact.phones[j];
      cell[phone.title] = phone.number;
      cell[phone.title] += phone.nonlocal ? "（外埠）" : "";
    }
    cells.push(cell);
  }
  const fileName = "CDTCC-2KT通讯录导出" + dateFormat();
  const data = XLSX.utils.json_to_sheet(cells);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, data, "通讯录");
  wb.Sheets["通讯录"]["!cols"] = Array.apply(null, new Array(10)).map(() => {
    return { wch: 20 };
  });
  XLSX.writeFile(wb, fileName + ".xlsx");
};

const parseTel = (telNum) => {
  return telNum.length == 11
    ? parseInt(telNum.substr(0, 1)) == 0 && parseInt(telNum.substr(1, 1)) > 2
      ? // 11位，且第1位等于0、第2位大于2：非省会4位区号+7位电话
        telNum.replace(/^(.{4})(.{4})(.*)$/, "$1 $2 $3")
      : // 11位，其余情况：手机或省会3位区号+8位电话
        telNum.replace(/^(.{3})(.*)(.{4})$/, "$1 $2 $3")
    : telNum.length == 8 || telNum.length == 7
    ? // 8位或7位：固话座机
      telNum.replace(/^(.{4})(.*)$/, "$1 $2")
    : // 其他未知情况
      telNum;
};

onMounted(() => {
  load();
});
</script>
